package com.bst.etl.batch.processor;


import com.bst.common.constant.JobConstant;
import com.bst.common.exception.base.BaseException;
import com.bst.etl.vo.JobShareDataVO;
import com.bst.system.framework.utils.MsgUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.batch.item.ItemProcessor;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class DimDataCheckProcessor implements ItemProcessor<Map<String,Object>, Map<String,Object>> {

    private JobShareDataVO jobShareDataVO;

    public DimDataCheckProcessor() {
    }

    public DimDataCheckProcessor(JobShareDataVO jobShareDataVO) {
        this.jobShareDataVO = jobShareDataVO;
    }

    @Override
    public Map process(Map<String,Object> origMap) throws Exception {
        if(origMap==null) return null;
        Map<String, Object> map = new HashMap<>();
        for(Map.Entry<String, Object> entry:origMap.entrySet()) {
            map.put(entry.getKey().toUpperCase(),entry.getValue());
        }
        String key,naDimfld;
        Object value,nameValue;
        Map<String,Object> dimData;
        for(Map.Entry<String,Object> entry:map.entrySet()) {
            key = entry.getKey();
            value = entry.getValue();
            if(value==null || StringUtils.isBlank(value.toString())) {
                value = "-99";
            } else if(key.startsWith(JobConstant.ID_DIM_PREX)) { //1 普通维度 2 可忽略维度 3 自动填充名称维度
                naDimfld = key.replace("ID_","NA_");
                if(!map.keySet().contains(naDimfld)) {
                    continue;
                }
                if("3".equals(jobShareDataVO.getJobDimVOMap().get(key).getSdDimtp())) {
                    if(value!=null) {
                        nameValue = jobShareDataVO.getJobDimVOMap().get(key).getData().get(value.toString());//测试异常情况下job执行状态在处理
                        if(nameValue==null) {
                            MsgUtil.sendMsg(JobConstant.MSG_CODE_C02,key+"中编码为["+value+"]的缺少对应名称请完善并重抽数据",null);
                            throw new BaseException(key+"中编码为["+value+"]的缺少对应名称请完善并重抽数据");
                        }
                    } else {
                        nameValue = null;
                    }
                    map.put(naDimfld,nameValue);
                } else if("1".equals(jobShareDataVO.getJobDimVOMap().get(key).getSdDimtp())) {
                    if((dimData=jobShareDataVO.getDimDataMap().get(key))==null) {
                        dimData = new ConcurrentHashMap<>();
                        jobShareDataVO.getDimDataMap().put(key,dimData);
                    }
                    naDimfld = key.replace("ID_","NA_");
                    nameValue = map.get(naDimfld);
                    if(nameValue==null) nameValue="-99";
                    dimData.put(value.toString(),nameValue);
                }
            }
            map.put(key,value);
        }
        return map;
    }
}